﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BFCOMAssistant
{
    public class BasicDataFormatLib
    {
        #region 16进制数转ASCII字符串
        public static string HexToASCII(byte[] buff, out string strData)
        {
            strData = "";
            char[] c = new char[buff.Length];
            try
            {
                for (int i = 0; i < buff.Length; i++)
                {
                    c[i] = Convert.ToChar(buff[i]);
                }

                strData = new string(c);
            }
            catch (Exception ex)
            {
                return ex.Message;
            }

            return "OK";
        }
        #endregion

        #region 将字符串strData转化成nd/2个16进制数，存放在rbuf中
        public static string StringToHexByteArr(string strData, out byte[] rbuf)
        {
            string tempData = System.Text.RegularExpressions.Regex.Replace(strData, @"\s", "");

            if (tempData.Length % 2 != 0)
            {
                rbuf = new byte[1];
                return "Byte length error";
            }
            else
            {
                rbuf = new byte[tempData.Length / 2];
            }

            for (int i = 0; i < tempData.Length / 2; i++)
            {
                try
                {
                    rbuf[i] = Convert.ToByte(tempData.Substring(i * 2, 2), 16);     //取字符串中的2个字符转成16进制  
                }
                catch (Exception ex)
                {
                    return ex.Message;
                }

            }
            return "OK";
        }
        #endregion
    }
}
